package fr.generali.accueilclient.gwt.client.ui.components.form.formitem.handler;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.TextBox;

public class PreventNonNumericEntriesHandler implements KeyPressHandler {

    private TextBox source;

    public PreventNonNumericEntriesHandler(TextBox source) {
        this.source = source;
    }

    @Override
    public void onKeyPress(KeyPressEvent event) {
        Boolean revert;

        int keyCode = event.getCharCode();
        if (keyCode != 0) {
            revert = !Character.isDigit((char ) keyCode);
        } else {
            keyCode = event.getNativeEvent().getKeyCode();
            revert =
                            (keyCode != KeyCodes.KEY_TAB) && (keyCode != KeyCodes.KEY_BACKSPACE)
                                            && (keyCode != KeyCodes.KEY_DELETE) && (keyCode != KeyCodes.KEY_ENTER)
                                            && (keyCode != KeyCodes.KEY_HOME) && (keyCode != KeyCodes.KEY_END)
                                            && (keyCode != KeyCodes.KEY_LEFT) && (keyCode != KeyCodes.KEY_UP)
                                            && (keyCode != KeyCodes.KEY_RIGHT) && (keyCode != KeyCodes.KEY_DOWN);
        }
        if (revert) {
            source.cancelKey();
        }
    }
}
